import type { AxiosRequestConfig } from "axios"
import { setAccessToken, setRefreshToken } from "../auth"
import { loadingService } from "./axios/loadingService"

// 在渲染进程中监听token过期事件
if (window.ipcRenderer) {
  window.ipcRenderer.on("auth-token-expired", (_event, data) => {
    console.log("收到token过期事件:", data)

    // 清除token
    setAccessToken("")
    setRefreshToken("")

    // 显示提示
    loadingService.showMessage(data.message || "登录状态已过期，请重新登录", "error")

    // 重定向到登录页
    console.log("准备重定向到登录页")
    setTimeout(() => {
      window.location.replace("/login")
    }, 100)
  })
}

// 创建HTTP请求客户端
class ElectronHttpClient {
  // 发送请求
  async request<T = any>(config: AxiosRequestConfig): Promise<T> {
    // 显示loading
    loadingService.show()

    try {
      const response = await window.ipcRenderer.invoke("http-request", config)
      console.log("HTTP请求成功:", response)

      // 隐藏loading
      loadingService.hide()

      if (response.success) {
        return response.data
      } else {
        // 检查是否是401错误，如果是但没有被主进程捕获，在这里也处理一下
        if (response.error?.status === 401 || response.error?.data?.code === 401) {
          // 手动触发token过期处理
          console.log("检测到401错误，清除token并重定向")
          setAccessToken("")
          setRefreshToken("")

          loadingService.showMessage("登录状态已过期，请重新登录", "error")

          // 重定向到登录页
          setTimeout(() => {
            window.location.replace("/login")
          }, 100)
        } else if (response.error?.message) {
          // 显示错误消息
          loadingService.showMessage(response.error.message, "error")
        }

        throw new Error(response.error?.message || "请求失败")
      }
    } catch (error: any) {
      // 隐藏loading
      loadingService.hide()

      console.error("HTTP请求失败:", error)

      // 显示错误消息
      loadingService.showMessage(error.message || "请求失败，请稍后重试", "error")

      throw error
    }
  }

  // GET请求
  async get<T = any>(url: string, config?: Omit<AxiosRequestConfig, "url" | "method">): Promise<T> {
    console.log("get-url====>", url)
    console.log("get-config====>", config)
    return this.request<T>({
      url,
      method: "GET",
      ...config,
    })
  }

  // POST请求（支持 JSON 和 x-www-form-urlencoded）
  async post<T = any>(url: string, data?: any, config?: Omit<AxiosRequestConfig, "url" | "method" | "data">): Promise<T> {
    console.log("post-url====>", url)
    console.log("post-data====>", data)
    console.log("post-config====>", config)

    const headers = config?.headers || {}
    let finalData = data

    if (headers["Content-Type"] === "application/x-www-form-urlencoded") {
      // 使用 URLSearchParams 编码
      finalData = new URLSearchParams(data).toString()
    }

    return this.request<T>({
      url,
      method: "POST",
      data: finalData,
      headers,
      ...config,
    })
  }

  // PUT请求
  async put<T = any>(url: string, data?: any, config?: Omit<AxiosRequestConfig, "url" | "method" | "data">): Promise<T> {
    return this.request<T>({
      url,
      method: "PUT",
      data,
      ...config,
    })
  }

  // DELETE请求
  async delete<T = any>(url: string, config?: Omit<AxiosRequestConfig, "url" | "method">): Promise<T> {
    return this.request<T>({
      url,
      method: "DELETE",
      ...config,
    })
  }
}

// 扩展window接口
declare global {
  interface Window {
    ElMessage?: {
      warning: (message: string) => void;
      error: (message: string) => void;
      success: (message: string) => void;
    };
  }
}

// 导出HTTP客户端实例
export const electronHttp = new ElectronHttpClient()
